package com.shujushow.chapter00.controller;

import com.shujushow.chapter00.exception.MyException;
import com.shujushow.chapter00.response.MyRestResponse;
import com.shujushow.chapter00.security.RedisConfig;
import com.shujushow.chapter00.security.ShiroRealmImpl.ShiroUser;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Date;

/**
 * Created by xinshu on 2016/4/1.
 */
@Controller
public class WelcomeController {

    @Value("${application.message: Hello World}")
    private String message = "Hello World";
    
    @Autowired
	private RedisConfig redisConfig;
    
    @RequestMapping("/welcome")
    public String welcome(Model model){
    	 Subject subject = SecurityUtils.getSubject();
    	 String name =((ShiroUser)subject.getPrincipals().getPrimaryPrincipal()).getName();
        model.addAttribute("time", new Date());
        model.addAttribute("message", this.message);
        model.addAttribute("name", name);
        return "welcome";
    }

    @RequestMapping("/fail")
    public String fail(){
        throw new MyException("Oh dear!");
    }

    @RequestMapping("/msg")
    public String msg(Model model){
        model.addAttribute("message", this.message);
        model.addAttribute("name", redisConfig.getPort());
    	return "welcome";
    }
    
    @RequestMapping("fail2")
    public String fail2(){
        throw new IllegalStateException();
    }

    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody
    MyRestResponse handleMyRuntimeException(MyException exception){
        return new MyRestResponse("Some data I want to send back to the client.");
    }

}
